package com.sinux.generality.provider.demo.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sinux.generality.basesupport.utils.exception.BaseReturnEnum;
import com.sinux.generality.basesupport.utils.tool.ServiceUtil;
import com.sinux.generality.provider.demo.entity.User;
import com.sinux.generality.provider.demo.mapper.UserMapper;
import com.sinux.generality.provider.demo.util.JwtUtils;
import com.sinux.generality.provider.demo.util.PasswordUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sinux
 * @since 2023-05-06
 */
//@Service
public class UserService extends ServiceImpl<UserMapper, User> {

    @Resource
    private UserMapper userMapper;

    @Resource
    private ServiceUtil serviceUtil;

    /**
     * 日志
     */
    public static final Logger LOGGER = LoggerFactory.getLogger(UserService.class);

    /**
     * 用户登录
     * @param user
     * @return
     */
    public Map<String, Object> login(User user) {
        // 获取手机号和密码
        String mobile = user.getMobile();
        String pwd = user.getPwd();

        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(pwd)) {
            return serviceUtil.returnError(BaseReturnEnum.PARA_ERROR);
        }

        // 判断用户是否存在
        User userInfo = getUserByMobile(mobile);
        if (userInfo == null) {
            return serviceUtil.returnError(BaseReturnEnum.USER_NOT_FOUND);
        }

        // 校验密码
        String realPwd = userInfo.getPwd();
        String salt = userInfo.getSalt();
        if (!PasswordUtils.getMD5Encryption(pwd, salt).equals(realPwd)) {
            return serviceUtil.returnError(BaseReturnEnum.USER_PASSWORD_ERROR);
        }
        return serviceUtil.returnSuccess(JwtUtils.getJwtToken(userInfo.getUserId(), userInfo.getNickName()));
    }

    /**
     * 根据手机号查询用户信息
     * @param mobile
     * @return
     */
    public User getUserByMobile(String mobile) {
        return userMapper.getUserByMobile(mobile);
    }

}
